import { createRouter, createWebHistory } from 'vue-router';
import LoginView from '@/views/LoginView.vue';
import HomeView from '@/views/HomeView.vue';
import PublicActivitiesView from '@/views/PublicActivitiesView.vue';
import PublicActivityDetailView from '@/views/PublicActivityDetailView.vue';
import ActivityManagementView from '@/views/ActivityManagementView.vue';

// 手动定义 BASE_URL
const BASE_URL = '/';

const router = createRouter({
    history: createWebHistory(BASE_URL),
    routes: [
        {
            path: '/login',
            name: 'login',
            component: LoginView
        },
        {
            path: '/',
            name: 'home',
            component: HomeView
        },
        {
            path: '/public-activities',
            name: 'publicActivities',
            component: PublicActivitiesView
        },
        {
            path: '/public-activities/:id',
            name: 'publicActivityDetail',
            component: PublicActivityDetailView
        },
        {
            path: '/activity-management',
            name: 'activityManagement',
            component: ActivityManagementView,
            beforeEnter: (to, from, next) => {
                const isAdmin = localStorage.getItem('username') === 'admin';
                if (!isAdmin) {
                    alert('无权限访问');
                    next('/');
                } else {
                    next();
                }
            }
        }
    ]
});

router.beforeEach((to, from, next) => {
    const isLoggedIn = localStorage.getItem('username')!== null;
    const requiresAuth = ['publicActivities', 'publicActivityDetail', 'activityManagement'].includes(to.name);
    if (requiresAuth &&!isLoggedIn) {
        next('/login');
    } else {
        next();
    }
});

export default router;
    